/*
 * @Author: wuqingchun
 * @Date: 2024-07-10 10:40:54
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-07-10 11:09:00
 */

#include <cerrno>
#include <cstring>

#include <thread>

#include "mp_epoller.h"

void __main_Producer(CMPEpoller& refEpoller)
{
    uint32_t uiObjectID = 1;
    uint32_t uiPostCount = 0;

    while (1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        int32_t iErr = refEpoller.Post(uiObjectID);
        if (iErr != 0)
        {
            printf("Post error, %s, %d\n", strerror(errno), iErr);
            break;
        }

        uiPostCount++;

        printf("PostCount: %u\n", uiPostCount);
    }

    refEpoller.Close();
}

void __main_Consumer(CMPEpoller& refEpoller)
{
    uint32_t uiObjectID = 1;
    CMPEpoller::MP_EP_OBJECT astObjects[1];
    uint32_t uiWaitCount = 0;

    while (1)
    {
        int32_t iErr = refEpoller.Wait(astObjects, 1, 1);
        if (iErr < 0)
        {
            printf("Wait error, %s\n", strerror(errno));
            break;
        }

        if (iErr > 0)
        {
            uiWaitCount++;
            printf("Ready object, %u\n", uiWaitCount);
        }
    }

    refEpoller.Close();
}

int main(int argc, char** argv)
{
    CMPEpoller objEpoller;

    int32_t iErr = objEpoller.Create("mpepoller", 1);
    if (iErr == -1)
    {
        return iErr;
    }

    if (argc > 1)
    {
        __main_Producer(objEpoller);
    }
    else
    {
        __main_Consumer(objEpoller);
    }
    
    return 0;
}